const stats = new Stats()
stats.showPanel(0)
document.body.appendChild(stats.dom)

const setting = {
    ballNum: 100,
    dtxx: 0.001,
    dtyy: 0.005,
    isTail: 'true'
}

const gui = new dat.GUI({ width: 320 })
const folder = gui.addFolder('基础')
folder.open()
const c1 = folder.add(setting, 'ballNum', 10, 200, 1)
const c2 = folder.add(setting, 'dtxx', 0.001, 0.01, 0.001)
const c3 = folder.add(setting, 'dtyy', 0.001, 0.01, 0.001)
const c4 = folder.add(setting, 'isTail', ['true', 'false'])

c1.onFinishChange(() => { clear(); initBalls() })

function Ball(x, y, color, size) {
    this.start = { x, y }
    this.target = { x: innerWidth / 2, y: innerHeight / 2 }
    this.x = x
    this.y = y
    this.tx = 0
    this.ty = 0
    this.txx = 0
    this.tyy = 0
    this.color = color
    this.size = size
    this.draw = function () {
        fill(color, 100, 100)
        circle(this.x, this.y, this.size)
    }
    this.update = function () {
        this.txx += setting.dtxx
        this.tx = sin(this.txx)
        this.x = this.start.x * (1 - this.tx) + this.target.x * this.tx
        this.tyy += setting.dtyy
        this.ty = cos(this.tyy)
        this.y = this.start.y * (1 - this.ty) + this.target.y * this.ty
        this.draw()
    }
}

let balls = []

function initBalls() {
    balls.length = 0
    for (let i = 0; i < setting.ballNum; i++) {
        const x = random(innerWidth)
        const y = random(innerHeight)
        const color = floor(random(100))
        const size = floor(random(5, 20))
        const ball = new Ball(x, y, color, size)
        balls.push(ball)
    }
}

function setup() {
    createCanvas(innerWidth, innerHeight)
    noStroke()
    frameRate(60)
    colorMode(HSB, 100)
    background(0)
    initBalls()
}

function draw() {
    stats.begin()
    if (setting.isTail === 'true') {
        background(0, 0.8)
    } else {
        clear()
        background(0)
    }
    balls.forEach(ball => {
        ball.update()
    })
    stats.end()
}
